<template>
  <v-container>
    <AdminCommonCURD :config="curdComponentConfig" :addClickListener="addClickListener"
      :filter-listener="filterListener" :importClickListener="importListener" />
    <v-data-table-server :hover="true" :fixed-header="true" :loading="listLoading" :headers="headers" :items="wordList"
      :height="tableHeight" item-value="wordId" show-select v-model:items-per-page="wordBo.pageSize"
      :items-length="total" @update:options="loadItems" items-per-page-text="每页数据量"
      :items-per-page-options="[10, 20, 30, 40, 50, 100]">
      <template v-slot:item.actions="{ item }">
        <v-icon v-hasPermi="['read-word-admin']" class="me-2" icon="mdi-eye-outline"
          @click="viewWordDetail(item.data)"></v-icon>
        <v-icon v-hasPermi="['update-word-admin']" class="me-2" icon="mdi-pencil-outline"
          @click="updateWordDialog(item.data)"></v-icon>
        <v-menu v-hasPermi="['read-word-resource-admin']" open-on-hover transition="slide-y-transition">
          <template v-slot:activator="{ props }">
            <v-icon class="me-2" icon="mdi-dots-vertical-circle-outline" v-bind="props"></v-icon>
          </template>
          <v-list>
            <v-list-item>
              <v-list-item-title @click="showTTSCatalogDialog(item.data)">查看音频资源</v-list-item-title>
              <v-list-item-title @click="showPageCodeDialog(item.data)">查看原页面代码</v-list-item-title>
            </v-list-item>
          </v-list>
        </v-menu>
        <v-icon v-hasPermi="['update-word-admin']" class="me-2" icon="mdi-delete-outline"
          @click="deleteWordDelete(item.data)"></v-icon>
      </template>
      <template v-slot:item.pronunciations="{ item }">
        <PronunciationComponent direction="vertical" :pronunciationProps="item.data.pronunciation" />
      </template>
    </v-data-table-server>
  </v-container>
  <v-dialog v-model="commonDialogConfig.visible" persistent :width="commonDialogConfig.width">
    <v-card :prepend-icon="commonDialogConfig.prependIcon" :title="commonDialogConfig.title">
      <v-card-text>
        <DIYWordComponent :labelList="labelList" :langList="langList" ref="diyWordComponent" :bookList="bookList"
          v-if="commonDialogConfig.name == 'save' || commonDialogConfig.name == 'update'"
          :mode="commonDialogConfig.name" />
        <AdminWordDetailComponent v-else-if="commonDialogConfig.name == 'word-detail'" ref="adminWordDetailComponent" />
        <div v-else-if="commonDialogConfig.name == 'delete'">
          <p>确认删除
            <strong style="color:#2196F3">{{ commonDialogConfig.content }}</strong>
          </p>
          <div>
            <v-checkbox v-model="deleteWordItemSelected" label="隐藏单词数据（软删除）" value="wordDataSoftDel"></v-checkbox>
            <v-checkbox v-model="deleteWordItemSelected" label="删除单词数据" value="wordDataDel"></v-checkbox>
            <v-checkbox v-model="deleteWordItemSelected" label="删除单词的页面文件" value="wordOriginalDataDel"></v-checkbox>
            <v-checkbox v-model="deleteWordItemSelected" label="删除单词的音频文件" value="wordVoiceDel"></v-checkbox>
          </div>
        </div>
        <!-- <p v-else-if="commonDialogConfig.name == 'delete'">确认删除
          <strong style="color:#2196F3">{{ commonDialogConfig.content }}</strong>
          ？
        </p> -->
        <WordQueryFormComponent v-else-if="commonDialogConfig.name == 'filter'" :wordBo="wordBo" :langList="langList" />
        <ImportWordComponent v-else-if="commonDialogConfig.name == 'import'" :labelList="labelList" :langList="langList"
          :bookList="bookList" ref="ImportWordComponent" :importResponseCallback="importResponseCallback" />
        <ShowCodeComponent v-else-if="commonDialogConfig.name == 'pageCode'" :codeContainerHeight="tableHeight + 'px'"
          ref="showCodeComponent" />
        <TTSCatalogTableComponent v-else-if="commonDialogConfig.name == 'ttsCatalog'" ref="ttsCatalogTableComponent"
          :tableHeight="tableHeight - 100" />
      </v-card-text>
      <template v-slot:actions>
        <v-spacer></v-spacer>
        <v-btn color="gray" @click="resetCommonDialog">
          取消
        </v-btn>
        <v-btn v-if="commonDialogConfig.name == 'save' || commonDialogConfig.name == 'update'" color="green"
          @click="saveDiyWord">
          确定
        </v-btn>
        <v-btn v-if="commonDialogConfig.name == 'delete'" color="red" @click="confirmDelete(commonDialogConfig.data)">
          确认删除
        </v-btn>
        <v-btn v-if="commonDialogConfig.name == 'filter'" color="blue" @click="doFilter">
          搜索
        </v-btn>
        <v-btn v-if="commonDialogConfig.name == 'import'" color="blue" @click="startImport">
          导入
        </v-btn>
      </template>
    </v-card>
  </v-dialog>
  <v-snackbar v-model="snackbar">
    {{ snackbarMsg }}
  </v-snackbar>
  <v-overlay :model-value="overlay" class="align-center justify-center">
    <v-progress-circular color="primary" indeterminate size="64"></v-progress-circular>
  </v-overlay>
</template>

<script>
import { adminDeletePresetWord, getAdminPresetWord } from "@/api/word";
import AdminCommonCURD from "@/components/AdminCommonCURD.vue";
import DIYWordComponent from '../../components/DIYWordComponent.vue'
import { langList } from "@/api/lang.js";
import { adminLabelList } from "@/api/label.js";
import { adminBookList } from "@/api/book.js";
import AdminWordDetailComponent from '@/components/AdminWordDetailComponent.vue';
import WordQueryFormComponent from '@/components/WordQueryFormComponent.vue';
import ImportWordComponent from '@/components/ImportWordComponent.vue';
import ShowCodeComponent from "@/components/ShowCodeComponent.vue";
import TTSCatalogTableComponent from '@/components/TTSCatalogTableComponent.vue';
import PronunciationComponent from '@/components/PronunciationComponent.vue';

export default {
  components: {
    AdminCommonCURD, DIYWordComponent, AdminWordDetailComponent, WordQueryFormComponent, ImportWordComponent,
    ShowCodeComponent,
    TTSCatalogTableComponent,
    PronunciationComponent
  },
  data() {
    return {
      commonDialogConfig: {
        prependIcon: undefined,
        title: undefined,
        name: undefined,
        visible: false,
        content: undefined,
        width: undefined,
        data: undefined
      },
      tableHeight: 300,
      listLoading: false,
      wordBo: {
        bookId: undefined,
        pageSize: 20,
        pageNum: 1,
        sortOrder: false,
      },
      total: 0,
      headers: [
        { title: "ID", align: "start", key: "wordId" },
        { title: "单词", align: "start", key: "word" },
        { title: "发音", align: "start", key: "pronunciations" },
        { title: "释意", align: "start", key: "explain" },
        // { title: "语种", align: "start", key: "language" },
        { title: "标签", align: "start", key: "label" },
        { title: "创建日期", align: "start", key: "createAt" },
        { title: "操作", align: "start", key: "actions" },
      ],
      deleteWordItemSelected:[],
      wordList: [],
      langList: [],
      labelList: [],
      bookList: [],
      langMap: {},
      snackbar: false,
      snackbarMsg: undefined,
      overlay: false,
      curdComponentConfig: {
        backwardBtn:{},
        addBtn: {},
        batchImportBtn: {},
        batchDeleteBtn: {},
        searchBtn: {},
      }
    };
  },
  created() {
    this.tableHeight = window.innerHeight - 64 - 56 - 58;
    this.getSelectData()
    this.curdComponentInit()
  },
  methods: {
    getSelectData() {
      langList({}).then(resp => {
        this.langList = resp.data
        this.langList.forEach(item => {
          this.langMap[item.langId] = item
        })
      })
      adminLabelList({}).then(resp => {
        this.labelList = resp.data
      })
      adminBookList().then(resp => {
        this.bookList = resp.rows
      })
    },
    getPresetWordList() {
      this.listLoading = true
      getAdminPresetWord(this.wordBo).then(resp => {
        // console.log('resp = ',resp);
        // this.wordList = resp.rows
        this.total = resp.total
        this.wordListHandler(resp.rows)
      }).finally(() => this.listLoading = false)
    },
    loadItems({ page, itemsPerPage }) {
      // console.log(page, itemsPerPage, sortBy);
      this.wordBo.pageNum = page
      this.wordBo.pageSize = itemsPerPage
      this.getPresetWordList()
    },
    wordListHandler(wordList) {
      this.wordList = []
      if (wordList == null) return
      wordList.forEach(wordItem => {
        this.wordList.push(this.singleWordHandler(wordItem))
      })
    },
    singleWordHandler(wordItem) {
      let singleWord = {}
      singleWord.data = wordItem
      singleWord.wordId = wordItem.wordId
      singleWord.word = wordItem.word
      // if(wordItem.langId!=null&&this.langMap[wordItem.langId]!=null)singleWord.language = this.langMap[wordItem.langId].root
      singleWord.createAt = this.formatTimestamp(wordItem.createAt)
      singleWord.meanSelfExplain = []
      singleWord.meanLocalExplain = []
      return singleWord
    },
    updateWordDialog(word) {
      this.commonDialogConfig.title = "修改单词"
      this.commonDialogConfig.name = 'update'
      this.commonDialogConfig.visible = true
      this.commonDialogConfig.prependIcon = 'mdi-update'
      setTimeout(() => {
        this.$refs.diyWordComponent.keep(word)
      }, 300);
    },
    viewWordDetail(word) {
      this.commonDialogConfig.title = "单词详情"
      this.commonDialogConfig.name = 'word-detail'
      this.commonDialogConfig.visible = true
      this.commonDialogConfig.prependIcon = 'mdi-eye'
      setTimeout(() => {
        this.$refs.adminWordDetailComponent.setWord(word)
      }, 100);
    },
    addClickListener() {
      this.commonDialogConfig.title = "添加单词"
      this.commonDialogConfig.name = 'save'
      this.commonDialogConfig.visible = true
      this.commonDialogConfig.prependIcon = 'mdi-plus-box'
    },
    filterListener() {
      this.commonDialogConfig.title = "条件搜索"
      this.commonDialogConfig.name = 'filter'
      this.commonDialogConfig.visible = true
      this.commonDialogConfig.prependIcon = 'mdi-magnify'
    },
    importListener() {
      this.commonDialogConfig.title = "单词批量导入"
      this.commonDialogConfig.name = 'import'
      this.commonDialogConfig.visible = true
      this.commonDialogConfig.prependIcon = 'mdi-import'
    },
    showPageCodeDialog(word) {
      this.commonDialogConfig.title = "查看页面代码：" + word.word
      this.commonDialogConfig.name = 'pageCode'
      this.commonDialogConfig.visible = true
      this.commonDialogConfig.prependIcon = 'mdi-xml'
      setTimeout(() => {
        this.$refs.showCodeComponent.getWordPageResource(word.word)
      }, 100);
    },
    showTTSCatalogDialog(word) {
      this.commonDialogConfig.title = "查看 " + word.word + ' 已关联的本地语音文件'
      this.commonDialogConfig.name = 'ttsCatalog'
      this.commonDialogConfig.visible = true
      this.commonDialogConfig.prependIcon = 'mdi-file'
      setTimeout(() => {
        this.$refs.ttsCatalogTableComponent.showWordTTSCatalog(word.word)
      }, 100);
    },
    deleteWordDelete(word) {
      this.commonDialogConfig.title = "删除单词"
      this.commonDialogConfig.name = 'delete'
      this.commonDialogConfig.visible = true
      this.commonDialogConfig.prependIcon = 'mdi-delete'
      this.commonDialogConfig.content = word.word
      this.commonDialogConfig.data = { wordIdList: word.wordId }
      // this.commonDialogConfig.width=300
    },
    doFilter() {
      this.loadItems({ page: 1, itemsPerPage: 20 })
      this.resetCommonDialog()
    },
    saveDiyWord() {
      this.$refs.diyWordComponent.save(this.commonDialogConfig.name, (result) => {
        if (result) {
          this.resetCommonDialog()
          this.getPresetWordList()
        }
      })
    },
    confirmDelete(wordList) {
      adminDeletePresetWord({wordIdList:wordList,deleteConfig:deleteWordItemSelected}).then(resp => {
        if (resp.code == 1) {
          this.resetCommonDialog()
          this.getPresetWordList()
          this.deleteWordItemSelected=[]
        }
      })
    },
    startImport() {
      this.$refs.ImportWordComponent.startTask()
    },
    resetCommonDialog() {
      this.commonDialogConfig = {}
    },
    importResponseCallback(resp) {
      this.snackbarMsg = resp.msg
      this.snackbar = true
      if (resp.code == 1) {
        this.resetCommonDialog()
        this.overlay = false
      }
    },
    formatTimestamp(timestamp) {
      let date = new Date(timestamp);
      let year = date.getFullYear();
      let month = ('0' + (date.getMonth() + 1)).slice(-2); // 加1是因为getMonth()返回的是0-11
      let day = ('0' + date.getDate()).slice(-2);
      let hour = ('0' + date.getHours()).slice(-2);
      let minute = ('0' + date.getMinutes()).slice(-2);
      let second = ('0' + date.getSeconds()).slice(-2);
      return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
    },
    curdComponentInit() {
      if (!this.$store.state.userPermissionArray.includes('read-word-admin'))
        this.showErrorPage = true
      else if (this.$store.state.userPermissionArray.includes('update-word-admin')) {
        this.curdComponentConfig.backwardBtn.visible = false
        this.curdComponentConfig.addBtn.visible = true
        this.curdComponentConfig.searchBtn.visible = true
        this.curdComponentConfig.batchImportBtn.visible = true
        this.curdComponentConfig.batchDeleteBtn.visible = true
      } else this.curdComponentConfig.searchBtn.visible = true
    }
  },
};
</script>

<style scoped>
@media (min-width: 1280px) {
  .v-container {
    max-width: 100%;
    padding: 10px;
  }
}
</style>